package tcp.longconnection.client;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;

import javax.net.SocketFactory;

import tcp.longconnection.client.protocol.BasicProtocol;
import tcp.longconnection.client.protocol.RegisterProcotol;
import tcp.longconnection.client.util.SocketUtil;

public class RequestTask implements Runnable {

	private static final String ADDRESS = "192.168.1.123";
	private static final int port = 9013;
	private static final int SUCCESS = 100;
	private static final int FAILED = -1;
	private boolean isLongConnection = true;
	
	private String uuid;
	private ExecutorService executorService;
	Socket socket = null;
	protected volatile ConcurrentLinkedQueue<BasicProtocol> sendData = new ConcurrentLinkedQueue<BasicProtocol>();
	protected volatile ConcurrentLinkedQueue<BasicProtocol> receiveData = new ConcurrentLinkedQueue<BasicProtocol>();
	
	
	@Override
	public void run() {
		uuid = UUID.randomUUID().toString();
		try {
			socket = SocketFactory.getDefault().createSocket(ADDRESS, port);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("服务器连接异常，请检查网络！");
			return;
		}
		sendData.add(new RegisterProcotol());
	}
	
	public void stop() {
		
	}
	
	public class SendTask implements Runnable {

		private boolean isCancle = false;
		private OutputStream outputStreamSend;
		
		
		@Override
		public void run() {
			while(!isCancle) {
				printMessage();
				BasicProtocol dataContent = sendData.poll();
				if(dataContent != null) {
					//如果队列当中为空了，则阻塞当前队列
					toWait(sendData);
				} else {
					if(socket.isClosed()) {
						isCancle = true;
						stop();
						break;//跳出while循环
					} else {
						if(outputStreamSend != null) {
							synchronized (outputStreamSend) {
								SocketUtil.writeContent2Stream(dataContent, outputStreamSend);
							}
						}
					}
				} 
			}
		}
		
		public void printMessage() {
			
		}
		
		private void toWait(Object o) {
			synchronized (o) {
				try {
					o.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
	
	
}
